package com.waimai.demo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waimai.demo.Service.OrderDetailService;
import com.waimai.demo.Service.OrdersService;
import com.waimai.demo.back.BaseContext;
import com.waimai.demo.back.R;
import com.waimai.demo.domain.OrderDetail;
import com.waimai.demo.domain.Orders;
import com.waimai.demo.dto.OrdersDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/order")

public class orderController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> page(Long page, Long pageSize) {
        Page<Orders> page1 = new Page(page, pageSize);
        Page<OrdersDto> page2 = new Page();
        Long id = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        lambdaQueryWrapper.eq(Orders::getUserId, id);
        List<Orders> ordersList = ordersService.list(lambdaQueryWrapper);
        ordersService.page(page1, lambdaQueryWrapper);
        BeanUtils.copyProperties(page1, page2, "records");
        List<OrdersDto> ordersDtoList = new LinkedList();
        for (Orders orders : ordersList) {
            OrdersDto ordersDto = new OrdersDto();
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper1 = new LambdaQueryWrapper();
            lambdaQueryWrapper1.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> list = orderDetailService.list(lambdaQueryWrapper1);
            BeanUtils.copyProperties(orders, ordersDto);
            ordersDto.setOrderDetails(list);
            ordersDtoList.add(ordersDto);
        }
        page2.setRecords(ordersDtoList);
        return R.success(page2);
    }

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        ordersService.submit(orders);
        return R.success("下单成功");
    }

}
